package org.kth.dks.planetlab;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.StringTokenizer;

import org.kth.dks.dks_comm.DKSRef;

public class HostUtils {

	public static int getDKSRefAsint(DKSRef ref) {
		System.out.println("IP=" + ref.getIP());
		System.out.println("long=" + getIpAsLong(ref.getIP()));
		System.out.println("int=" + (int) getIpAsLong(ref.getIP()));

		return (int) getIpAsLong(ref.getIP());
	}

	public static long getIpAsLong(String ip) {
		long ret = 0, octet;
		StringTokenizer st = new StringTokenizer(ip, ".");

		if (st.hasMoreTokens()) {
			octet = Integer.parseInt(st.nextToken());
			ret = octet;
		} else {
			return -1;
		}
		if (st.hasMoreTokens()) {
			octet = Integer.parseInt(st.nextToken());
			ret = (ret << 8) + octet;
		} else {
			return -1;
		}
		if (st.hasMoreTokens()) {
			octet = Integer.parseInt(st.nextToken());
			ret = (ret << 8) + octet;
		} else {
			return -1;
		}
		if (st.hasMoreTokens()) {
			octet = Integer.parseInt(st.nextToken());
			ret = (ret << 8) + octet;
		} else {
			return -1;
		}

		return ret;
	}

	private static String getIpAsString(int ip) {
		int octet = ip & 255;
		String ret = new Integer(octet).toString();
		ip >>= 8;
		octet = ip & 255;
		ret = new Integer(octet).toString() + "." + ret;
		ip >>= 8;
		octet = ip & 255;
		ret = new Integer(octet).toString() + "." + ret;
		ip >>= 8;
		octet = ip & 255;
		ret = new Integer(octet).toString() + "." + ret;

		return ret;
	}

	private static Inet4Address getNonLoopbackInet4Address() {
		try {
			Enumeration ifaces = NetworkInterface.getNetworkInterfaces();

			while (ifaces.hasMoreElements()) {
				NetworkInterface iface = (NetworkInterface) ifaces.nextElement();

				if (iface.getName().matches("eth*")) {
					Enumeration addresses = iface.getInetAddresses();

					while (addresses.hasMoreElements()) {
						InetAddress address = (InetAddress) addresses.nextElement();

						if (address.getAddress().length == 32) {
							return (Inet4Address) address;
						}
					}
				}
			}
			return null;
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		}
	}
}
